<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="form" :model="listQueryForm" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item prop="strActivityname" label="活动名称">
              <el-input v-model="listQueryForm.strActivityname" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item prop="iLocation" label="活动位置">
              <el-select v-model="listQueryForm.iLocation" placeholder="请选择活动位置">
                <el-option
                  v-for="item in actLocation"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item prop="iOrgsysnum" label="所属机构">
              <el-cascader
                v-model="listQueryForm.iOrgsysnum"
                :show-all-levels="false"
                :options="options"
                :props="{ expandTrigger: 'hover', value:'strOrgnum',label:'strOrgname',children: 'yhlist' ,checkStrictly: true }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="strEndtime" label="截止日期">
              <el-date-picker
                v-model="listQueryForm.strEndtime"
                type="datetime"
                prefix-icon="el-icon-date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="fetchList">搜索</el-button>
            <el-button @click="$refs['form'].resetFields()">重置</el-button>
            <el-button type="primary" @click="handleRow">添加</el-button>
            <!-- <el-button type="danger">删除</el-button> -->
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table v-loading="tableLoading" :data="tableData" style="width: 100%" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center" width="80" />
      <el-table-column prop="STR_ACTIVITYNAME" label="活动名称" width="180" />
      <el-table-column prop="STR_SHOWIMG" label="活动展示图" width="180" align="center">
        <template slot-scope="{row}">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.STR_SHOWIMG"
            :preview-src-list="[row.STR_SHOWIMG]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="STR_IMG" label="活动缩略图" width="180" align="center">
        <template slot-scope="{row}">
          <el-image style="width: 100px; height: 100px" :src="row.STR_IMG" />
        </template>
      </el-table-column>
      <el-table-column prop="STR_LINK" label="活动网址" width="180" />
      <el-table-column prop="I_LOCATION" label="活动位置" width="180">
        <template slot-scope="{row}">{{ row.I_LOCATION | statusFilter }}</template>
      </el-table-column>
      <el-table-column prop="STR_ORGNAME" label="所属机构" width="180" />
      <el-table-column prop="STR_USERNAME" label="操作者" width="180" />
      <el-table-column prop="STR_ENDTIME" label="截止日期" width="180" />
      <el-table-column label="操作" width="180">
        <template slot-scope="{row}">
          <template v-if="row.iOrgsysnum === iOrgsysnum || iOrgsysnum === -1">
            <el-button size="mini" type="primary" @click="handleModifyStatus(row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
          <template v-else>/</template>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQueryForm.pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="fetchList"
    />

    <el-dialog
      :key="isResouceShow"
      :visible.sync="dialogPvVisible"
      :append-to-body="true"
      :title="mTitle"
      :data-case="dataCase"
      width="70%"
      :close-on-click-modal="false"
      :before-close="handleCancel"
    >
      <div>
        <el-form
          ref="formDialog"
          :model="form"
          :rules="rules"
          label-position="right"
          label-width="100px"
        >
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item prop="strActivityname" label="活动名称">
                <el-input v-model="form.strActivityname" class="inptw200" placeholder="请输入活动名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="strLink" label="活动网址">
                <el-input v-model="form.strLink" class="inptw200" placeholder="请输入活动网址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="iLocation" label="活动位置">
                <el-select v-model="form.iLocation" placeholder="请选择活动位置">
                  <el-option
                    v-for="item in actLocation"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="iOrgsysnum" label="所属机构">
                <el-cascader
                  v-model="form.iOrgsysnum"
                  :show-all-levels="false"
                  :options="options"
                  :props="{ expandTrigger: 'hover', value:'strOrgnum',label:'strOrgname',children: 'yhlist' ,checkStrictly: true }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="strEndtime" label="截止日期">
                <el-date-picker
                  v-model="form.strEndtime"
                  type="datetime"
                  prefix-icon="el-icon-date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="expireTimeOption"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="strShowimg" label="活动展示图">
                <el-upload
                  class="avatar-uploader"
                  :action="baseImgRUL"
                  name="uploadFile"
                  :show-file-list="false"
                  :on-success="(response, file)=>{handleSuccess(response, file, 'form', 'strShowimg','strShowimgsize'),$refs['formDialog'].clearValidate('strShowimg')}"
                  :before-upload="beforeUpload"
                >
                  <img v-if="form.strShowimg" :src="form.strShowimg" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                  <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="strImg" label="活动缩略图">
                <el-upload
                  class="avatar-uploader"
                  :action="baseImgRUL"
                  name="uploadFile"
                  :show-file-list="false"
                  :on-success="(response, file)=>handleSuccess(response, file, 'form', 'strImg' , '', 'strImgsize')"
                  :before-upload="beforeUpload"
                >
                  <img v-if="form.strImg" :src="form.strImg" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button v-if="mTitle === diaTitle.add" type="primary" @click.prevent="handleConfirm">确认</el-button>
        <el-button v-else type="primary" @click.prevent="handleConfirModify">修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getActList,
  deleteActRow,
  addActInfo,
  getOrglists,
  updateActInfo
} from '../../api/addTag'
import Pagination from '@/components/Pagination'
import mixins from '@/mixins/uploadImg'
import { validateValue } from '../../utils/validateForm'
import { validURL } from '../../utils/validate'
import { mapGetters } from 'vuex'
// import mixins1 from './mixins/index'
var validateURL = (rule, value, callback) => {
  if (value !== '') {
    if (!validURL(value)) {
      callback(new Error('请输入正确活动网址'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
export default {
  name: 'ActivityPage',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const actLocation = {
        '1': '广告',
        '2': '海报'
      }
      return actLocation[status]
    }
  },
  mixins: [mixins],
  props: {},
  data() {
    return {
      dialogPvVisible: false,
      tableLoading: false,
      mTitle: '',
      isResouceShow: 0,
      diaTitle: {
        add: '添加活动',
        edit: '修改活动'
      },
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now() - 8.64e7
        }
      },
      value1: '',
      dataCase: 1, // 1新增0修改
      options: [],
      form: {
        strActivityname: '',
        iOrgsysnum: '',
        strLink: '',
        iLocation: '',
        strImg: '',
        strShowimg: '',
        strEndtime: '',
        strOperator: this.name,
        strImgsize: '', // 活动缩略图大小
        strShowimgsize: '' // 活动展示图大小
      },
      actLocation: [
        {
          value: '1',
          label: '广告'
        },
        {
          value: '2',
          label: '海报'
        }
      ],
      optionResoltion: [],
      listQueryForm: {
        strActivityname: '',
        iLocation: '',
        iOrgsysnum: '',
        strEndtime: '',
        iOrgnum: this.iOrgsysnum,
        pagenum: 1
      },
      model: '',
      total: 0,
      limit: 5,
      layout: 'total, prev, pager, next, jumper',
      baseAppType: [],
      tableData: [],
      rules: {
        strActivityname: [
          {
            required: true,
            validator: validateValue,
            message: '请输入活动名称',
            trigger: 'blur'
          }
        ],
        strLink: [{ validator: validateURL }],
        iLocation: [
          { required: true, message: '请选择活动位置', trigger: 'change' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        strShowimg: [
          { required: true, message: '请上传活动缩略图', trigger: 'blur' }
        ],
        strImg: [
          { required: true, message: '请上传活动展示图', trigger: 'blur' }
        ],
        strEndtime: [
          { required: true, message: '请选择截止时间', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum', 'name', 'userID'])
  },
  created() {
    this.fetchList()
    this.fetchOrglist()
    this.form.strOperator = this.name || 'Super Admin'
    // console.log(typeof this.iOrgsysnum)
    // if (this.iOrgsysnum !== -1) {
    //   getParentNumArr({ iOrgsysnum: this.iOrgsysnum }).then(res => {
    //     if (res.data.indexOf(',') > 0) {
    //       this.form.iOrgsysnum = res.data.split(',')
    //     } else {
    //       this.form.iOrgsysnum.push(res.data)
    //     }
    //   })
    // } else {
    //   this.form.iOrgsysnum = this.iOrgsysnum
    // }
    this.mTitle = this.diaTitle.add
  },
  mounted() {},
  methods: {
    fetchList() {
      // 获取列表
      this.tableLoading = true
      if (this.listQueryForm.iOrgsysnum instanceof Array) {
        this.listQueryForm.iOrgsysnum = this.listQueryForm.iOrgsysnum.splice(
          -1
        )[0]
      }
      this.listQueryForm.iOrgnum = this.iOrgsysnum.toString()
      getActList(this.listQueryForm)
        .then(res => {
          this.tableData = res.data
          this.total = !res.total ? 0 : res.total
          setTimeout(() => {
            this.tableLoading = false
          }, 1000)
        })
        .catch(err => {
          this.tableLoading = false
          console.log(err)
        })
    },
    fetchOrglist() {
      getOrglists({ iOrgnum: this.iOrgsysnum }).then(res => {
        if (!res.data) {
          return false
        }
        if (Array.isArray(res.data)) {
          this.options = res.data
        } else {
          this.options.push(res.data)
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        deleteActRow({ idInfo: [row.ID] }).then(res => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 500,
            onClose: () => {
              this.fetchList()
            }
          })
        })
      })
    },
    handleModifyStatus(row) {
      this.dialogPvVisible = true
      this.form.strActivityname = row.STR_ACTIVITYNAME
      this.form.iOrgsysnum = row.I_ORGSYSNUM.toString()
      this.form.strLink = row.STR_LINK
      this.form.iLocation = row.I_LOCATION.toString()
      this.form.strImg = row.STR_IMG
      this.form.strShowimg = row.STR_SHOWIMG
      this.form.strOperator = this.userID
      this.form.strEndtime = row.STR_ENDTIME
      this.form.id = row.ID
      this.form.strImgsize = row.STR_IMGSIZE // 活动缩略图大小
      this.form.strShowimgsize = row.STR_SHOWIMGSIZE // 活动展示图大小
      // this.form.id = row.ID
      this.mTitle = this.diaTitle.edit
    },
    handleRow() {
      this.form = {
        strActivityname: '',
        strOperator: this.userID,
        iOrgsysnum: '',
        strLink: '',
        iLocation: '',
        strImg: '',
        strShowimg: '',
        strEndtime: '',
        strImgsize: '', // 活动缩略图大小
        strShowimgsize: '' // 活动展示图大小
      }
      this.mTitle = this.diaTitle.add
      this.dialogPvVisible = true
      this.$nextTick(() => {
        // this.$refs['formDialog'].resetFields()
        this.$refs['formDialog'].clearValidate()
      })
    },
    handleConfirm() {
      this.$refs['formDialog'].validate(valid => {
        if (valid) {
          if (this.form.iOrgsysnum instanceof Array) {
            this.form.iOrgsysnum = this.form.iOrgsysnum.splice(-1)[0]
          }
          addActInfo(this.form)
            .then(res => {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.fetchList()
            })
            .catch(err => {
              console.log(err)
            })
          this.dialogPvVisible = false
          this.$refs['formDialog'].resetFields()
          this.form.iOrgsysnum = ''
          ++this.isResouceShow
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleConfirModify() {
      this.$refs['formDialog'].validate(valid => {
        if (valid) {
          if (this.form.iOrgsysnum instanceof Array) {
            this.form.iOrgsysnum = this.form.iOrgsysnum.splice(-1)[0]
          }
          updateActInfo(this.form)
            .then(res => {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.dialogPvVisible = false
              this.mTitle = this.diaTitle.add
              this.fetchList()
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.dialogPvVisible = false
      this.$refs['formDialog'].resetFields()
      this.mTitle = this.diaTitle.add
      this.form = {
        strActivityname: '',
        iOrgsysnum: '',
        strLink: '',
        iLocation: '',
        strImg: '',
        strShowimg: '',
        strEndtime: '',
        strOperator: this.name || 'Super Admin'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.marginTop {
  margin-top: 20px;
}
</style>
